import time

from PyQt6.QtCore import QThread, pyqtSignal, Qt
import Global
from PyQt6.QtGui import QColor, QBrush


class TableViewThread(QThread):
    update_table_signal = pyqtSignal()

    STATUS_COLOR = {
        '联机': {'bg': '#FFA500', 'text': '#FFFFFF'},
        '运行': {'bg': '#008000', 'text': '#FFFFFF'},
        '停止': {'bg': '#FF0000', 'text': '#FFFFFF'},
        '脱机': {'bg': '#FFFFFF', 'text': '#000000'}
    }

    def __init__(self, parent=None):
        super().__init__(parent)
        self.running = True
        self.last_visible_rows = []
        self.last_update_time = 0

    def run(self):
        try:
            update_interval = 300  # 更新间隔1000毫秒
            while self.running:
                if Global.mainWindow is None:
                    self.msleep(50)
                    continue

                # 直接获取当前可见行范围并立即更新
                if Global.mainWindow and Global.mainWindow.model:
                    first_visible = Global.mainWindow.model.first_visible_row
                    last_visible = Global.mainWindow.model.last_visible_row

                    # 立即更新可见行范围并打印
                    current_visible = list(range(first_visible, last_visible + 1))
                    self.last_visible_rows = current_visible

                    # 立即触发颜色更新
                    #self.update_visible_colors()

                # 处理可见行数据
                has_updates = False
                field_list = Global.G_Config.get('FieldList', [])

                for index in self.last_visible_rows:
                    if index >= len(Global.G_Game):
                        continue

                    game_data = Global.G_Game[index]

                    for col, field in enumerate(field_list, start=1):
                        key = field.get('key', '')
                        if key in game_data.data:
                            value = str(game_data.data[key]) if field.get('number', False) else game_data.data[key]

                            model_index = Global.mainWindow.model.index(index, col)
                            if Global.mainWindow.model.setData(model_index, value, Qt.ItemDataRole.DisplayRole):
                                has_updates = True

                            # 处理状态颜色
                            #if key == 'status':
                            self.update_status_color(index, col, value)


                if has_updates:
                    self.update_table_signal.emit()
                self.totalAccount = 0
                self.uploadAccount = 0
                self.hour_produce_count =0
                for game in Global.G_Game:
                    self.totalAccount += int(game.data['produceAccount'])
                    self.uploadAccount += int(game.data['produceUploadCount'])

                current_time = int(time.time())
                time_elapsed_hours = (current_time - Global.G_ScriptRunTime) / 3600
                if time_elapsed_hours >= 1:
                    # 实际运行超过 1 小时，直接计算
                    self.hour_produce_count = self.totalAccount / time_elapsed_hours
                else:
                    # 不足 1 小时，按当前速率预估
                    self.hour_produce_count = self.totalAccount
                # 批量收集状态栏更新数据
                status_updates = {
                    'total': str(self.totalAccount),
                    'upload': str(self.uploadAccount),
                    'hour_produce': str(int(self.hour_produce_count))
                }
                
                # 使用信号槽机制在主线程空闲时更新
                current_time = int(time.time())
                if Global.mainWindow and current_time - self.last_update_time >= 2:
                    Global.mainWindow.status_bar_updates.emit(status_updates)
                    self.last_update_time = current_time
                self.msleep(update_interval)
        except Exception as e:
            Global.G_Log.error(f"刷新表格异常:{e}")

    def update_visible_colors(self):
        """专门处理可见行的颜色更新，用于滚动后快速响应"""
        try:
            if Global.mainWindow is None or Global.mainWindow.model is None:
                return

            # 直接使用当前存储的可见行范围
            visible_rows = self.last_visible_rows

            field_list = Global.G_Config.get('FieldList', [])
            has_updates = False

            # 批量处理可见行的状态颜色
            for index in visible_rows:
                if index >= len(Global.G_Game):
                    continue

                game_data = Global.G_Game[index]

                # 只处理状态字段的颜色
                for col, field in enumerate(field_list, start=1):
                    key = field.get('key', '')
                    if key == 'status' and key in game_data.data:
                        value = game_data.data[key]
                        if self.update_status_color(index, col, value):
                            has_updates = True

            # 立即应用更新
            if has_updates:
                self.update_table_signal.emit()

            # 强制刷新视图
            Global.mainWindow.tableView.viewport().update()

        except Exception as e:
            Global.G_Log.error(f"更新可见行颜色异常:{e}")

    def update_status_color(self, index, col, value):
        """处理状态颜色更新"""
        try:
            if Global.mainWindow is None:
                return

            color_config = self.STATUS_COLOR.get(value, self.STATUS_COLOR['脱机'])
            model_index = Global.mainWindow.model.index(index, col)

            # 直接设置颜色
            Global.mainWindow.model.setData(
                model_index,
                QBrush(QColor(color_config['bg'])),
                Qt.ItemDataRole.BackgroundRole
            )
            Global.mainWindow.model.setData(
                model_index,
                QBrush(QColor(color_config['text'])),
                Qt.ItemDataRole.ForegroundRole
            )
            return True
        except Exception as e:
            Global.G_Log.error(f"更新状态颜色异常:{e}")
            return False

    def stop(self):
        self.running = False